package com.yaohe.consumer.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yaohe.consumer.R;
import com.yaohe.consumer.core.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class EcouponListAdapter extends ArrayAdapter<EcouponItem>{
	
    private ListView listView;
    private AsyncImageLoader asyncImageLoader;

    public EcouponListAdapter(Activity activity, List<EcouponItem> imageAndTexts, ListView listView) {
        super(activity, 0, imageAndTexts);
        this.listView = listView;
        asyncImageLoader = new AsyncImageLoader();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Activity activity = (Activity) getContext();

        // Inflate the views from XML
        View rowView = convertView;
        ViewCache viewCache;
        if (rowView == null) {
            LayoutInflater inflater = activity.getLayoutInflater();
            rowView = inflater.inflate(R.layout.image_and_text_row, null);
            viewCache = new ViewCache(rowView);
            rowView.setTag(viewCache);
        } else {
            viewCache = (ViewCache) rowView.getTag();
        }
        EcouponItem imageAndText = getItem(position);

        // Load the image and set it on the ImageView
        String imageUrl = imageAndText.getLogoPicUri();
        ImageView imageView = viewCache.getImageView();
        String tag = imageUrl + "_" + String.valueOf(position);
        
        imageView.setTag(tag);
        Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, position, new ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl, int index) {
            	String tag2 = imageUrl + "_" + String.valueOf(index); 
                ImageView imageViewByTag = (ImageView) listView.findViewWithTag(tag2);
                if (imageViewByTag != null) {
                    imageViewByTag.setImageDrawable(imageDrawable);
                }
            }
        });
		if (cachedImage == null) {
			imageView.setImageResource(R.drawable.piclogo_loading);
		}else{
			imageView.setImageDrawable(cachedImage);
		}
        // Set the text on the TextView
        TextView textView = viewCache.getTextView();
        textView.setText(imageAndText.getDiscountInfo());

        return rowView;
    }
}
